package com.ib.algokit.marketscan;

import org.activequant.core.domainmodel.InstrumentSpecification;
import org.activequant.core.domainmodel.marketscanner.MarketScanChange;
import org.activequant.core.domainmodel.marketscanner.MarketScanChange.ChangeType;
import org.activequant.util.pattern.events.IEventListener;

import com.ib.algokit.TraderProxy;
/**
 * MarketScanChangeListenerHandlingStrategy extends ThreadPerInstrumentEventHandlingStrategy implements IEventListener&lt;MarketScanChange&gt;.<br/>
 * This is the listener for MarketScanChanges that starts a separate Thread to analyze an Instrument that seems interesting.<br/>
 * Holds the associated ema(EMA) variable. It also defines a nested InstrumentAnalyzingThread class.
 * @author dmisev
 *
 */
public class MarketScanChangeListenerHandlingStrategy extends ThreadPerInstrumentBaseStrategy implements IEventListener<MarketScanChange> {
	/**
	 * Constructs a ThreadPerInstrumentEventHandlingStrategy(implements IEventListener&lt;MarketScanChange&gt;) using the given ema(EMA) to set its
	 * associated ema(EMA).<br/>
	 * It also iterates the existing Positions and starts an InstrumentAnalyzingThread for those whose quantity is not 0
	 * @param ema
	 */
	public MarketScanChangeListenerHandlingStrategy(TraderProxy ema){
		super(ema);
//		InstrumentSpecification spec=new InstrumentSpecification(new Symbol("AAPL"), "SMART", "IB", Currency.USD, SecurityType.OPTION);
//		analyzeInstrument(spec);
		
//		analyzePositions();		
	}
	/**
	 * This gets notified of any MarketScanChanges and then we choose which ones we will analyze by starting an InstrumentAnalyzingThread fo them
	 */
	public void eventFired(MarketScanChange marketScanChange) {
		if(ema.getAnalyzerThreads().size()>=MAX_ALLOWED_INSTRUMENTS)//for testing only
			return;		
		if(!((marketScanChange.getChangeType()==ChangeType.INSTRUMENT_MOVED_UP)||(marketScanChange.getChangeType()==ChangeType.INSTRUMENT_ADDED))){
			return;
		}
//		if(!marketScanChange.getScanCriteria().getScanCode().equals("LOW_OPT_VOLUME_PUT_CALL_RATIO")){
//			return;
//		}
		InstrumentSpecification instrumentSpecification = marketScanChange.getInstrumentSpecificationDetails().getInstrumentSpecification();
		InstrumentAnalyzingThread instrumentAnalyzingThread = ema.getAnalyzerThreads().get(instrumentSpecification);
		if (instrumentAnalyzingThread == null) {
			//instrumentSpecification=ema.getInstrumentSpecificationDao().update(instrumentSpecification);			
			instrumentAnalyzingThread = new InstrumentAnalyzingThread(instrumentSpecification);
			ema.getAnalyzerThreads().put(instrumentSpecification, instrumentAnalyzingThread);
			startAnalyzerThread(instrumentAnalyzingThread);			
		}
		instrumentAnalyzingThread.enqueue(marketScanChange);
	}
}